package com.Blog.www.service.Impl;

import com.Blog.www.constant.DataConstant;
import com.Blog.www.constant.PageConstant;
import com.Blog.www.constant.SqlConstant;
import com.Blog.www.constant.TipsConstant;
import com.Blog.www.dao.Impl.LikeDaoImpl;
import com.Blog.www.dao.Impl.UserDaoImpl;
import com.Blog.www.dao.LikeDao;
import com.Blog.www.dao.UserDao;
import com.Blog.www.po.PageBean;
import com.Blog.www.po.User;
import com.Blog.www.service.UserService;
import com.Blog.www.utils.DataExamine;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 用户操作实现类
 *
 * @author 君未洋
 */
public class UserServiceImpl implements UserService {
    private static UserDao dao = new UserDaoImpl();
    private static LikeDao likeDao = new LikeDaoImpl();
    private static DataExamine date = new DataExamine();

    @Override
    public String getCheckCode() {
        String base = "0123456789ABCDEFGHIJKMNPQRSJUBWXYZabcdefghjkmnpqrsjubwxyz";
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 1; i <= 4; i++) {
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        return sb.toString();
    }

    @Override
    public User login(String account, String password) {
        if (date.numberExamine(account) || date.passwordExamine(password)) {
            return null;
        }
        User user = new User();
        user.setAccount(Integer.parseInt(account));
        user.setPassword(password);
        return dao.login(user);
    }

    @Override
    public User regist(String username, String password) {
        if ("".equals(username) || username == null || "".equals(password) || password == null || date.passwordExamine(password)) {
            return null;
        }
        User user = new User();
        user.setAccount(account());
        //调用account方法获取随机的用户账号
        user.setUsername(username);
        user.setPassword(password);
        if (dao.regist(user, SqlConstant.IDENTITY_B)) {
            return user;
            //如果成功就返回用户
        } else {
            return null;
            //失败就返回空;
        }
    }

    @Override
    public Integer account() {
        //先随机生成一个4位account
        Random random = new Random();
        int account = random.nextInt(8999) + 1000;
        //调用dao方法查询是否有重复的account
        while (dao.getAccount(account)) {
            account = random.nextInt(8999) + 1000;
        }
        return account;
    }

    @Override
    public boolean managerLogin(User user, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (SqlConstant.IDENTITY_C.equals(user.getIdentity()) || SqlConstant.IDENTITY_D.equals(user.getIdentity())) {
            if (SqlConstant.STATUS_B.equals(user.getStatus())) {
                //成功就跳转管理员界面,失败就返回
                resp.sendRedirect(req.getContextPath() + "/ManagerHome.jsp");
                return true;
            }
        }
        req.setAttribute(PageConstant.USER_D, TipsConstant.USER_LOGIN_F);
        req.getRequestDispatcher("/UserBlog/findBlogByPage").forward(req, resp);
        //跳转回原来主页
        return false;
    }

    @Override
    public PageBean<User> findUserList(String getCurrentPage, String getRows, String status, String identity) {
        if (getCurrentPage == null || "".equals(getCurrentPage) || date.numberExamine(getCurrentPage)) {
            getCurrentPage = "1";
        }

        if (getRows == null || "".equals(getRows) || date.numberExamine(getRows)) {
            getRows = "5";
        }
        PageBean<User> pb = new PageBean<User>();
        //设置参数
        int currentPage = Integer.parseInt(getCurrentPage);
        int rows = Integer.parseInt(getRows);
        if (currentPage <= 0) {
            currentPage = 1;
            //防止跳转到后面
        }
        //调用dao查询总记录
        int totalCount = dao.findUserTotalCount(status, identity);
        pb.setTotalCount(totalCount);
        //设置到pb中

        //5.计算总页码
        int totalPage = (totalCount % rows) == 0 ? (totalCount / rows) : (totalCount / rows + 1);
        pb.setTotalPage(totalPage);

        if (currentPage > totalPage) {
            currentPage = totalPage;
        }
        pb.setCurrentPage(currentPage);
        pb.setRows(rows);

        //这里是调用dao索引list集合
        int start = (currentPage - 1) * rows;
        List<User> list = dao.findUserList(start, rows, status, identity);
        pb.setList(list);
        return pb;
    }

    @Override
    public void changeUser(String[] userIds, String status) {
        //调用dao方法一个一个操作
        for (String userId : userIds) {
            if (date.numberExamine(userId)) {
                return;
            }
            int id = Integer.parseInt(userId);
            dao.changerUser(id, status);
            //再调用Blog的dao方法把用户相对应的文章也封禁了
            /*           blogDao.changeUserBlog(id,status);*/
        }
    }

    @Override
    public Boolean recall(String username, String account, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = dao.getUser(username, account);
        if (user == null) {
            req.removeAttribute(PageConstant.USER_E);
            req.setAttribute(PageConstant.USER_E, TipsConstant.USER_LOGIN_B);
            return false;
        } else {
            req.removeAttribute(DataConstant.USER_E);
            req.setAttribute(DataConstant.USER_E, user);
            req.getRequestDispatcher("/recall.jsp").forward(req, resp);
            return true;
        }
    }

    @Override
    public boolean changePassword(User user, String password, String oldPassword, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (!user.getPassword().equals(oldPassword)) {
            req.setAttribute(PageConstant.USER_A, TipsConstant.USER_MODIFY_A);
            req.getRequestDispatcher("/modifyPassword.jsp").forward(req, resp);
            return false;
        }
        if (user.getPassword().equals(password)) {
            req.setAttribute(PageConstant.USER_A, TipsConstant.USER_MODIFY_B);
            req.getRequestDispatcher("/modifyPassword.jsp").forward(req, resp);
            return false;
        }
        int id = user.getId();
        //都没问题就可以修改密码了
        if (dao.changePassword(id, password)) {
            req.removeAttribute(DataConstant.USER_A);
            req.setAttribute(PageConstant.USER_C, "修改成功,您的新密码为" + password);
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return true;
        }
        req.setAttribute(PageConstant.USER_A, TipsConstant.BLOG_OPERATION_G);
        req.getRequestDispatcher("/modifyPassword.jsp").forward(req, resp);
        return false;
    }

    @Override
    public HttpServletRequest examineCheckCode(HttpServletRequest req, HttpServletResponse resp, String verifyCode, String checkCode_server, String msg, String address) throws ServletException, IOException {
        if (verifyCode == null || !verifyCode.equalsIgnoreCase(checkCode_server)) {
            //输入的验证码不正常
            req.setAttribute(msg, TipsConstant.USER_LOGIN_C);
            req.getRequestDispatcher(address).forward(req, resp);
            return null;
        }
        return req;

    }

    @Override
    public HttpServletRequest examineLogin(HttpServletRequest req, HttpServletResponse resp, User login, String auto) throws ServletException, IOException {

        if (login == null) {
            //登录失败
            req.setAttribute(PageConstant.USER_C, TipsConstant.USER_LOGIN_D);
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        } else if (SqlConstant.STATUS_C.equals(login.getStatus())) {
            req.setAttribute(PageConstant.USER_C, TipsConstant.USER_LOGIN_E);
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        } else {
            Long date = System.currentTimeMillis();
            if(date<login.getLastTime()){
                req.setAttribute(PageConstant.USER_C,TipsConstant.USER_LOGIN_H+((login.getLastTime()-date)/60000)+"分钟");
                        req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }
            else{
                //把用户的lasttime修改下
                dao.banTime(login.getId()+"",System.currentTimeMillis());
                req.getSession().setAttribute(DataConstant.USER_A, login);
                if (!(auto == null || "".equals(auto))) {
                    Cookie c = new Cookie(SqlConstant.AUTO_LOGIN, login.getId() + "");
                    c.setMaxAge(60 * 60 * 24 * 30);
                    //先保存个一个月把
                    c.setPath(req.getContextPath());
                    //设置作用路径为根路径
                    resp.addCookie(c);
                }
                resp.sendRedirect(req.getContextPath() + "/UserBlog/findBlogByPage");
            }
        }
        return req;
    }

    @Override
    public HttpServletRequest examineRegist(HttpServletRequest req, HttpServletResponse resp, User regist) throws ServletException, IOException {
        if (regist == null) {
            req.setAttribute("login_msg", TipsConstant.USER_REGIST_A);
            req.getRequestDispatcher("/regist.jsp").forward(req, resp);
        } else {
            req.removeAttribute("login_msg");
            req.setAttribute("login_msg", TipsConstant.USER_REGIST_B);
            req.getSession().setAttribute(DataConstant.USER_A, regist);
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
        return req;
    }

    @Override
    public String getUsername(String getCuid) {
        if (getCuid == null || "".equals(getCuid) || date.numberExamine(getCuid)) {
            return null;
        }
        int cuid = Integer.parseInt(getCuid);
        User user = dao.getUser(cuid, null);
        if (user == null) {
            return null;
        } else {
            return user.getUsername();
        }
    }

    @Override
    public User touristLogin() {
        User user = new User();
        user.setAccount(account());
        //获取随机代码的账号
        user.setPassword(SqlConstant.PASSWORD_A);
        user.setUsername(SqlConstant.IDENTITY_A + new Date());
        //封装下游客账号
        //调用注册的方法来传入数据
        if (dao.regist(user, SqlConstant.IDENTITY_A)) {
            return login(user.getAccount() + "", user.getPassword());
        } else {
            return null;
        }
    }

    @Override
    public User autoLogin(Integer userId) {
        if (userId == null || userId < 0) {
            return null;
        } else {
            User user = dao.getUser(userId, null);
            if (SqlConstant.IDENTITY_A.equals(user.getIdentity())) {
                user.setFlag(false);
            } else {
                user.setFlag(true);
            }
            return user;
        }
    }

    @Override
    public HttpServletResponse deleteCookie(Cookie[] cs, HttpServletResponse resp) {
        //获取数据,并遍历
        if (cs != null) {
            for (Cookie c : cs) {
                if (SqlConstant.AUTO_LOGIN.equals(c.getName())) {
                    //遍历cookie然后擦除数据
                    c.setMaxAge(0);
                    //先查询下这个用户
                    User user = dao.getUser(Integer.parseInt(c.getValue()), null);
                    if (SqlConstant.IDENTITY_A.equals(user.getIdentity())) {
                        //顺手把相对的收藏和用户也删除了
                        likeDao.delete(c.getValue(), null);
                        dao.delete(c.getValue());
                    }
                    resp.addCookie(c);
                    return resp;
                }
            }
        }
        return resp;
    }

    @Override
    public Boolean addImg(Part part, User user) {
        //确定上传路径
        String path = DataConstant.IMG_HEAD_PATH;
        //创建指向路径的File对象
        File file = new File(path);
        //file.exists()文件(文件夹或文件路径正确)存在返回true,不存在返回false
        if (!file.exists()) {
            //创建文件夹，把路径中不存在的路径一下创建
            file.mkdirs();
        }

        String imgName = user.getId() + ".jpg";
        //文件上传
        try {
            part.write(path + "/" + imgName);
            //调用dao方法把user对应的头像数据写入
            return dao.addImg(imgName, user);
        } catch (IOException e) {
            return false;
        }
    }

    @Override
    public HttpServletRequest banTime(String[] userIds, Integer banTime, HttpServletRequest req) {
        if(date.numberExamine(userIds)||date.numberExamine(banTime+"")){
            req.setAttribute(PageConstant.USER_B,TipsConstant.DATA_EXCEPTION);
        }
        else{
            Long time = System.currentTimeMillis()+banTime*60000;
            for (String userId : userIds) {
                //一个个封禁楼
                dao.banTime(userId,time);
            }
            req.setAttribute(PageConstant.USER_B,TipsConstant.BLOG_OPERATION_B);
        }
        return req;
    }
}


